﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SimpleTaskManager.WebUI.Models
{
    /// <summary>
    /// An action result for binary data
    /// </summary>
    public class BinaryResult : ActionResult
    {
        private byte[] _fileBinary;
        private string _contentType;
        private string _fileName;

        /// <summary>
        /// Creates a new instance of the binary action result.
        /// </summary>
        /// <param name="fileBinary">The binary data to return</param>
        /// <param name="contentType">The content type of the file</param>
        /// <param name="fileName">The original filename</param>
        public BinaryResult(byte[] fileBinary, string contentType, string fileName)
        {
            _fileBinary = fileBinary;
            _contentType = contentType;
            _fileName = fileName;
        }

        /// <summary>
        /// Processes the result of an action method.
        /// </summary>
        /// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = _contentType;
            context.HttpContext.Response.AddHeader("Content-Disposition", "filename=" + _fileName);

            if (_fileBinary != null)
            {
                context.HttpContext.Response.BinaryWrite(_fileBinary);
            }
        }
    }
}
